package com.news.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {

	private static String driverName;
	private static String url;
	private static String username;
	private static String password;
	
	/**
	 * 静态块:程序在执行期间只会执行一次
	 * 
	 * jdbc中常用的四个字符串，一般情况下不会硬编码，而是定义在资源文件（属性文件.properties）中，动态读取
	 */
	static {
		try {
			//动态读取jdbc中使用四个字符串信息
			Properties prop = new Properties();
			prop.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
			driverName = prop.getProperty("jdbc.mysql.driver");
			url = prop.getProperty("jdbc.mysql.url");
			username = prop.getProperty("jdbc.mysql.username");
			password = prop.getProperty("jdbc.mysql.password");
			//加载驱动类，注册驱动
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 1.获取连接对象
	 */
	public static Connection getConnection(){
		try {
			Connection connection = DriverManager.getConnection(url, username, password);
			return connection;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 2.关闭资源
	 */
	public static void close(Connection connect, Statement stmt, ResultSet rs){
		try {
			if(rs != null){
				rs.close();
			}
			if(stmt != null){
				stmt.close();
			}
			if(connect != null){
				connect.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
}
